class_name DarkSpace
extends Node2D

@export var width: int = 1
@export var height: int = 1
@onready var block_parent: Node2D = $BlockParent
@onready var collision_shape_2d: CollisionShape2D = $Area2D/CollisionShape2D
var block_size: int = 16

const FATE_BLOCK = preload("uid://dcu7i1voj0beo")

@onready var light_occluder_2d: LightOccluder2D = $LightOccluder2D
var level: Level = null


func _ready() -> void:
	level = get_tree().current_scene as Level
	
	collision_shape_2d.shape = collision_shape_2d.shape.duplicate()
	light_occluder_2d.occluder = light_occluder_2d.occluder.duplicate()
	
	for x in range(width):
		for y in range(height):
			var inst = FATE_BLOCK.instantiate() as Node2D
			block_parent.add_child(inst)
			inst.position = Vector2(x * block_size, y * block_size)
	
	var shape = collision_shape_2d.shape as RectangleShape2D
	shape.size = Vector2(block_size * width, block_size * height)
	collision_shape_2d.position = Vector2(block_size * width / 2.0, block_size * height / 2.0)
	
	var poly = light_occluder_2d.occluder.polygon
	poly[0] = Vector2(0, 0)
	poly[1] = Vector2(block_size * width, 0)
	poly[2] = Vector2(block_size * width, block_size * height)
	poly[3] = Vector2(0, block_size * height)
	light_occluder_2d.occluder.polygon = poly
	

func _on_area_2d_body_entered(body: Node2D) -> void:
	var tween_alpha = create_tween()
	tween_alpha.tween_property(block_parent, "modulate:a", 0, 0.3) \
	.set_trans(Tween.TRANS_CUBIC) \
	.set_ease(Tween.EASE_IN).from_current()
	
	light_occluder_2d.visible = false


func _on_area_2d_body_exited(body: Node2D) -> void:
	var tween_alpha = create_tween()
	tween_alpha.tween_property(block_parent, "modulate:a", 1.0, 0.3) \
	.set_trans(Tween.TRANS_CUBIC) \
	.set_ease(Tween.EASE_OUT).from_current()
	
	light_occluder_2d.visible = true
		
		
func disable_physics():
	collision_shape_2d.disabled = true
	

func enable_physics():
	collision_shape_2d.disabled = false
